package com.yunc.modules.quartz.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunc.base.schedule.SchedulerUtils;
import com.yunc.modules.quartz.entity.SysJob;
import com.yunc.modules.quartz.mapper.SysJobMapper;
import com.yunc.modules.quartz.service.ISysJobService;
import lombok.RequiredArgsConstructor;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 定时任务
 * @author congcong tao
 * @create 2018/11/3 下午9:41
 */
@Service("sysJobService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper,SysJob> implements ISysJobService {

    private final SysJobMapper sysJobMapper;
    private final Scheduler scheduler;

    @PostConstruct
    public void initScheduleJob() throws SchedulerException {
        SysJob recordJob = new SysJob();
        List<SysJob> jobs = this.list(new QueryWrapper<>(recordJob));
        if (CollUtil.isEmpty(jobs)) {
            return;
        }
        for (SysJob record : jobs) {
            CronTrigger cronTrigger = SchedulerUtils.getCronTrigger(scheduler, record.getId());
            if (cronTrigger == null) {
                SchedulerUtils.createScheduleJob(scheduler, record);
            } else {
                SchedulerUtils.updateScheduleJob(scheduler, record);
            }
        }
    }
}
